human_bytes
A Rust crate & cli to convert bytes into human-readable values.
It can return either KiB/MiB/GiB/TiB or KB/MB/GB/TB by disabling the si-units
feature.
1 KiB = 1024 B, 1 KB = 1000 B
It supports from 0 bytes to several yottabytes (I cannot tell how many because I have to use u128
s
to fit a single YB)
Usage
As a CLI
- (Optional) Install Just
- Build:
- With just:
just build-binary
- Plain cargo:
cargo build --release --features 'build-binary fast' --bin hb
- With just:
- Copy
target/release/hb
to somewhere in your$PATH
- Run
hb <bytes>
orecho <bytes> | hb
As a library
Add to your Cargo.toml
:
[]
= "0.4"
# or, to disable the SI Units:
= { = "0.4", = false }
And then
use human_bytes;
assert_eq!;
// or
assert_eq!;
// ________________________________/
// |
// | Needed only when you're using `u64` values,
// | because `f64` doesn't implement `std::convert::From<u64>`
// With the `si-units` feature disabled:
assert_eq!;
The crate is dependency-free, but you can boost the speed by enabling the fast
feature,
which switches from using std::format!
to ryu
to convert floats to strings.
[]
= { = "0.4", = ["fast"] }
About
The code is based on a PHP function I found here.
It is useful because you don't have to provide a prefix, it does it on its own.
It'll always return 1 MiB
instead of 1024 KiB
It has some tests I wrote to check that the conversion is correct, and it returns decimals (e.g. 16.5 GiB
)
Changelog
Check the CHANGELOG.md
License
BSD 2-clause (c) 2020-2022 Namkhai B.